<?php
error_reporting(E_ALL);
date_default_timezone_set("Europe/London");
ini_set('display_errors', '1');

$topdirectory="../MSWebGUI";
include $topdirectory.'/FileList.php';

$topdirectory=".";
include $topdirectory.'/FileList.php';

$thisPage;

function DeleteEvent($database )
{
		$table = new DBTable($database,$_POST['DBTableName']);
//		$tableStructure = $table->getTableStructure();
//		$keys = array_keys($tableStructure);

		$timeNow = new DateTime("now");
		$sql = "UPDATE ".$_POST['DBTableName']." SET DeletedWhen = '".$timeNow->format("Y-m-d H:i")."', DeletedBy = '".$_POST['UserID']."' ";
		$sql .= " WHERE ".$table->getPrimaryKey()."=".$_POST['RecordID'];

//		echo $sql;

		$database->ExecuteSQL($sql);
}

function InsertEvent($database, $action)
{
		$table = new DBTable($database,$_POST['DBTableName']);
		$tableStructure = $table->getTableStructure();
//		$keys = array_keys($tableStructure);
//		print_r($tableStructure);
//		echo "<br><br>";

//		echo "Action = ".$action."<br>\n";

		$keys = array();
					
		foreach($_POST as $key => $value)
		{
//			echo $key."<br>";
			$parts = explode('_',$key,3);
//			print_r ($parts)."<br>";
			if($parts[0]=="InsertRecord")
			{
	/*			if($parts[1]!=$Table)
				{
					if($Table!="")$InsertID=InsertIntoTable($Database,$Table,$FieldArray,$ParentTableID);
					if($ParentTableID==-1)$ParentTableID=$InsertID;
					$FieldArray=array();
					$Table = $parts[1];
				}*/
//				print $value."<br>";
				
				if(isset($tableStructure[$parts[2]]))
				{
					if(($parts[2]=="OriginalRecordID")&&($action=="InsertRecord"))$value=0;
					$keys[$parts[2]] = $value;
				}
			}
		}
		
//		print_r($keys);
/*		$keyValues = array();
		foreach($keys as $key)
//			if (($key != $table->getPrimaryKey())&&($key != "CreatedBy")&&($key != "CreatedWhen")&&($key != "DeletedBy")&&($key != "DeletedWhen")&&($tableStructure[$key]!="enum('multienum')"))
				$keyValues[$key] = $_POST["InsertRecord_".$_POST['DBTableName']."_".$key];
		print_r($keyValues);
*/				
/********************************************************/
		$repeatWeeks = 0;
		if(isset($_POST['RepeatWeeks']))$repeatWeeks = $_POST['RepeatWeeks'];
		for($i=0;$i <= $repeatWeeks;$i++)
		{
			
			$sql = "INSERT INTO ".$_POST['DBTableName']." (";
			$sql.= "CreatedWhen,CreatedBy,";

			foreach($keys as $key => $value)
			{
				if (($key != $table->getPrimaryKey())&&($key != "CreatedBy")&&($key != "CreatedWhen")&&($key != "DeletedBy")&&($key != "DeletedWhen")&&($tableStructure[$key]!="enum('multienum')"))
					$sql .= $key.",";
			}
			$sql = substr($sql,0,strlen($sql)-1).") VALUES (";
			$datetime = new DateTime("now");
			$sql.= "'".$datetime->format("Y-m-d H:i")."',".$_POST['UserID'].",";
			foreach($keys as $key => $value)
			{
//				echo $key."<br>";
				if (($key != $table->getPrimaryKey())&&($key != "CreatedBy")&&($key != "CreatedWhen")&&($key != "DeletedBy")&&($key != "DeletedWhen")&&($tableStructure[$key]!="enum('multienum')"))
					$sql .= "'".addslashes($value)."',";
			}
			$sql = substr($sql,0,strlen($sql)-1).")";
			
//			echo "sql = ".$sql."<br>\n";

			$database->ExecuteSQL($sql);
//			echo $sql.mysql_error();
			$EventID = mysql_insert_id();

			// are there any special fields (eg multienumerations)

			foreach($keys as $key => $valuearray)
			{
				if($tableStructure[$key]=="enum('multienum')")
					{
					foreach($valuearray as $value)
						{
						$sql = "INSERT INTO ".$key."s (EventID,".$key."NameID) VALUES (".$EventID.",".$value.")";
//						echo $sql.mysql_error();
						$database->ExecuteSQL($sql);

						}
					
					}
			}

//			echo $keyValues['Start'];
			if(isset($keys['Start']))
			{
				$time = new DateTime($keys['Start']);
				date_modify($time,"+7 day");
				$keys['Start']=$time->format("Y-m-d H:i");
			}

//			echo $keyValues['End'];
			if(isset($keys['End']))
			{
				$time = new DateTime($keys['End']);
				date_modify($time,"+7 day");
				$keys['End']=$time->format("Y-m-d H:i");
			}

//			echo ((new DateTime($keyValues['Start']))->modify("+7 day"))->format("Y-m-d H:i");

//			($keyValues['Start']) = ((new DateTime($keyValues['Start']))->modify("+7 day"))->format("Y-m-d H:i");
//			($keyValues['End']) = ((new DateTime($keyValues['End']))->modify("+7 day"))->format("Y-m-d H:i");
//			$keyValues['End']->modify("+7 day");
		}

/******************************************************************/


}

function UpdateEvent($database,$action)
{
	DeleteEvent($database );
	InsertEvent($database,$action );
}


$action = "";
if(isset($_POST))
{
	if (isset($_POST['Action']))
	{
		$action = $_POST['Action'];
	}
}

$view = "";
if(isset($_POST))
{
	if (isset($_POST['View']))
	{
		$view = $_POST['View'];
	}
}

$callingPage = "";
if(isset($_POST))
{
	if (isset($_POST['CallingPage']))
	{
		$callingPage = $_POST['CallingPage'];
	}
}

$xml = simplexml_load_file('config/config.xml');

$databaseXML = $xml->Database;

$database = new Database($databaseXML->Server,$databaseXML->Database,$databaseXML->Username,$databaseXML->Password);

switch($action)
{
	case 'Home':
		$thisPage = new PageHome();
		break;

	case 'ListEventsDiary':
		$thisPage = new PageDiary();
		break;

	case 'ListEventsList':
		$thisPage = new PageListEvents();
		break;

	case 'ListEvents':
		if($view =="Diary")
			$thisPage = new PageDiary();
		else
			$thisPage = new PageListEvents();
		break;

	case 'EditRecord':
	case 'NewRecord':
		$thisPage = new PageEditRecord();
		break;

	case 'DeleteRecord':
		DeleteEvent($database );
		if($view =="Diary")
			$thisPage = new PageDiary();
		else
			$thisPage = new PageListEvents();
		if($callingPage <> "")
		{
			if($callingPage =="Diary")
				$thisPage = new PageDiary();
			if($callingPage =="Directory")
				$thisPage = new PageDirectory();
		}
		break;

	case 'InsertRecord':
		InsertEvent($database,$action );
		if($view =="Diary")
			$thisPage = new PageDiary();
		else
			$thisPage = new PageListEvents();
		if($callingPage <> "")
		{
			if($callingPage =="Diary")
				$thisPage = new PageDiary();
			if($callingPage =="Directory")
				$thisPage = new PageDirectory();
		}
		break;

	case 'UpdateRecord':
		UpdateEvent($database,$action );
		if($view =="Diary")
			$thisPage = new PageDiary();
		else
			$thisPage = new PageListEvents();
		if($callingPage <> "")
		{
			if($callingPage =="Diary")
				$thisPage = new PageDiary();
			if($callingPage =="Directory")
				$thisPage = new PageDirectory();
		}
		break;

	case 'EventReport':
		$thisPage = new PageEventReport();
		break;

	case 'Directory';
		$thisPage = new PageDirectory();
		break;

	case 'Messages';
		$thisPage = new PageMessages();
		break;

	case 'Diary';
		$thisPage = new PageDiary();
		break;

	case 'Help';
		$thisPage = new PageHelp();
		break;

	case 'Logoff';
		$sql="UPDATE UserSessions SET Expires = '2010-01-01 01:00:00' WHERE SessionID = '".$_POST['SessionID']."' AND Username = '".$_POST['User'];
//		echo $sql;
		$database->ExecuteSql($sql);
		$thisPage = new PageLogon();
		break;

		
	default:
		$thisPage = new PageHome();
		break;
}					

$theAuthenticator = new Authenticator();
$theAuthenticator->setDatabase($database);
$thisPage->setAuthenticator($theAuthenticator);
$thisPage->setDatabase($database);


if ($thisPage->isAuthenticated())
	{
	$sql = "SELECT m.SnapUserID, m.SnapUserGroupID, u.SnapUserID, g.GroupName
		FROM 
		(SnapUserGroupMembers AS m
		INNER JOIN SnapUsers AS u ON m.SnapUserID = u.SnapUserID)
		INNER JOIN SnapUserGroups as g ON g.SnapUserGroupID = m.SnapUserGroupID
		WHERE u.SnapUserID = ".$thisPage->getUserID();

	$database->ExecuteSQL($sql);
	$row = $database->getRow();
	$thisPage->setUserGroup($row['GroupName']);
//	echo $row['GroupName'];
	echo $thisPage->getHTML();
	}

?>

